package ltd.dujiabao.dualwrite.datasource;

import org.springframework.jdbc.datasource.AbstractDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author Bowie Du
 * @date 2025/11/1 00:42
 */

public class DualWriteDataSource extends AbstractDataSource {
    private final DataSource priorityDataSource;
    private final DataSource secondaryDataSource;

    public DualWriteDataSource(DataSource priorityDataSource, DataSource secondaryDataSource) {
        this.priorityDataSource = priorityDataSource;
        this.secondaryDataSource = secondaryDataSource;
    }


    @Override
    public Connection getConnection() throws SQLException {
        return new DualWriteConnection(
                priorityDataSource.getConnection(),
                secondaryDataSource.getConnection()
        );
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return new DualWriteConnection(
                priorityDataSource.getConnection(username, password),
                secondaryDataSource.getConnection(username, password)
        );
    }
}
